package com.itheima.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.common.BaseContext;
import com.itheima.common.R;
import com.itheima.common.RedisResultKey;
import com.itheima.entity.Employee;
import com.itheima.entity.User;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 王磊
 * @date 2022/5/9
 */
@Slf4j
@WebFilter(filterName = " MyFilter", urlPatterns = "/*")
public class MyFilter implements Filter {
    private static final AntPathMatcher MATCHER = new AntPathMatcher();

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //获取当前请求路径
        String uri = request.getRequestURI();
        //定义不需要拦截的请求路径
        String[] uris = new String[]{
                "/employee/login",
                "/employee/logout",
                "/backend/**",
                "/front/**",
                "/user/sendMsg",
                "/user/login"
        };
        //判断本次请求要不要处理
        for (String s : uris) {
            if (MATCHER.match(s, uri)) {
                log.info("拦截到请求{},不需要处理", uri);
                filterChain.doFilter(request, response);
                return;
            }
        }
        //判断员工是否登入
        User user = (User) request.getSession().getAttribute("user");
        if (user != null) {
            BaseContext.setCurrentId(user.getId(    ));
            filterChain.doFilter(request, response);
            log.info("拦截到请求,员工已登入");
            return;
        }
        //判断用户是否登入
        Employee employee = (Employee) request.getSession().getAttribute("employee");
        if (employee != null) {
            BaseContext.setCurrentId(employee.getId());
            filterChain.doFilter(request, response);
            log.info("拦截到请求,用户已登入");
            return;
        }

        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        log.info("拦截到请求,用户未登入");
    }
}